package com.android.tabtestpack;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.R;
import com.android.PopFax.ExampleHandler;
import com.android.PopFax.ParsedExampleDataSet;

public class Inbox extends Activity implements Runnable,OnClickListener{
	/** Called when the activity is first created. */

	EditText userName;
	EditText password;
	private ProgressDialog pd ;
	ArrayAdapter<String> aa;
	ListView listItems;
	TableLayout tl;
	ArrayList<ArrayList<String>> dataFromDataBase;
	//TableRow tr[] = new TableRow[dataFromDataBase.size()];/* Create a array of TableRow */
	//TextView [] textViews = new TextView[dataFromDataBase.size()*4];/* Create a array of TextView */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inbox);
		tl = (TableLayout)findViewById(R.id.myTableLayout);
		pd = ProgressDialog.show(this, "Please Wait..", "Getting results..", true,false);

		Thread thread = new Thread(this);
		thread.start();
	}



	public void run() {
		try {
			HashMap<String,String> data= new HashMap<String, String>();
			data.put("action","retrieve_incoming_fax_list");
			//	data.put("username",userName.getText().toString());
			data.put("username","himanshu_virmani@yahoo.co.in");
			//		data.put("password",password.getText().toString());
			data.put("password","f927xu9a");
			data.put("dateFrom","2010-04-13 01:00:00");
			data.put("dateTo","2010-04-15 23:00:00");

			InputStream toastData= (doSubmit("https://api.popfax.com/api-server.php", data));

			/* Get a SAXParser from the SAXPArserFactory. */ 
			SAXParserFactory spf = SAXParserFactory.newInstance(); 
			SAXParser sp = spf.newSAXParser(); 

			/* Get the XMLReader of the SAXParser we created. */ 
			XMLReader xr = sp.getXMLReader(); 
			/* Create a new ContentHandler and apply it to the XML-Reader*/ 
			ExampleHandler myExampleHandler = new ExampleHandler(); 
			xr.setContentHandler(myExampleHandler); 

			/* Parse the xml-data from our URL. */ 
			xr.parse(new InputSource(toastData)); 
			/* Parsing has finished. */ 

			/* Our ExampleHandler now provides the parsed data to us. */ 
			ParsedExampleDataSet parsedExampleDataSet = 
				myExampleHandler.getParsedData(); 
			/*Get data from ParsedExampleDataSet in HashMap*/
			dataFromDataBase = new ArrayList<ArrayList<String>>();
			dataFromDataBase = parsedExampleDataSet.getRowWiseData();
			/* Set the result to be displayed in our GUI. */ 
			System.out.println(dataFromDataBase.get(0));
			System.out.println(dataFromDataBase.get(1));
			System.out.println(dataFromDataBase.size());
			
			TableRow tr[] = new TableRow[dataFromDataBase.size()+1];/* Create a array of TableRow */
			TextView [] textViews = new TextView[dataFromDataBase.size()*4 ];/* Create a array of TextView */
	        /* Find Tablelayout defined in main.xml */ 
			textViews[0] = new TextView(this);
            textViews[0].setText("FROM");
            textViews[0].setWidth(100);
            textViews[1] = new TextView(this);
            textViews[1].setText("PAGES");
            textViews[1].setWidth(100);
            textViews[2] = new TextView(this);
            textViews[2].setText("DATE-TIME");
            textViews[2].setWidth(100);
            tr[0]=new TableRow(this);
            tr[0].addView(textViews[0]);
            tr[0].addView(textViews[1]);
            tr[0].addView(textViews[2]);
            tr[0].setFocusable(true);
            tr[0].setFocusableInTouchMode(true);
         
            /*Perform OnClick on each row*/ 
            tr[0].setOnClickListener(this);
            /* Add row to TableLayout. */ 
            tl.addView(tr[0]);
		//		 Log.d("before loop",dataFromDataBase.size());
	             /*Adding content to rows*/
	             for(int i=0;i<dataFromDataBase.size();i++)
	             {
	      //       Log.d("in loop",dataFromDataBase.get(i+1).get(1));
	             textViews[i+1] = new TextView(this);
	             textViews[i+1].setText(dataFromDataBase.get(i).get(1));
	             textViews[i+1].setWidth(80);
	             textViews[i+2] = new TextView(this);
	             textViews[i+2].setText(dataFromDataBase.get(i).get(3));
	             textViews[i+2].setWidth(80);
	             textViews[i+3] = new TextView(this);
	             textViews[i+3].setText(dataFromDataBase.get(i).get(2));
	               tr[i+1]=new TableRow(this);
	               tr[i+1].addView(textViews[i+1]);
	               tr[i+1].addView(textViews[i+2]);
	               tr[i+1].addView(textViews[i+3]);
	              
	             tr[i+1].setFocusable(true);
	             tr[i+1].setFocusableInTouchMode(true);
	          
	             /*Perform OnClick on each row*/ 
	             tr[i+1].setOnClickListener(this);
	             /* Add row to TableLayout. */ 
	             tl.addView(tr[i+1]);
	             }     


			
			
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
		handler.sendEmptyMessage(0);
	}




	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			pd.dismiss();
			// Toast.makeText(getApplicationContext(),finalResult, Toast.LENGTH_SHORT).show();
			//                    if(.equals("Logged In Successfully"))
			//                    {
			//                    	
			//                    }


		}
	};



	
	public void onClick(View v) {
		//need to take faxid associted to row
//		for(int j=0;j<dataFromDataBase.size();j++)
//		{
//			if(v==tr[j])
//			{
//				Toast.makeText(getApplicationContext(),"Fax Id ="+dataFromDataBase.get(j).get(0), Toast.LENGTH_SHORT).show();
//				
//			}
//		}
		
	}



	public InputStream doSubmit(String url, HashMap <String,String> data)throws Exception{


		try{

			URL siteUrl= new URL(url);
			HttpURLConnection conn= (HttpURLConnection)siteUrl.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			DataOutputStream dataOutputStream=new DataOutputStream(conn.getOutputStream());

			Set keys=data.keySet();
			Iterator iter= keys.iterator();
			String content="";
			for(int m=0;iter.hasNext();m++){
				Object key=iter.next();
				if(m!=0)
				{
					content +="&";
				}
				content +=key+"="+URLEncoder.encode(data.get(key),"UTF-8");
			}


			dataOutputStream.writeBytes(content);
			dataOutputStream.flush();
			dataOutputStream.close();

			/*
	BufferedReader bufferedReader= new BufferedReader(new InputStreamReader (conn.getInputStream()));
	String line="";
	String retLine = "";
	while ((line=bufferedReader.readLine())!= null){
		System.out.println(line);
		retLine = retLine + line;
	}

	bufferedReader.close();*/
			return conn.getInputStream();

		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}



}